// FiveDoc.cpp : implementation of the CFiveDoc class
//

#include "stdafx.h"
#include "Five.h"

#include "FiveDoc.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFiveDoc

IMPLEMENT_DYNCREATE(CFiveDoc, CDocument)

BEGIN_MESSAGE_MAP(CFiveDoc, CDocument)
	//{{AFX_MSG_MAP(CFiveDoc)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFiveDoc construction/destruction

CFiveDoc::CFiveDoc()
{
	// TODO: add one-time construction code here
	m_bStart = false;
	cp = NULL;
}

CFiveDoc::~CFiveDoc()
{
}

BOOL CFiveDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)
	m_cb.Init();
	
	return TRUE;
}



/////////////////////////////////////////////////////////////////////////////
// CFiveDoc serialization

void CFiveDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
	}
	else
	{
		// TODO: add loading code here
	}
}

/////////////////////////////////////////////////////////////////////////////
// CFiveDoc diagnostics

#ifdef _DEBUG
void CFiveDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CFiveDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CFiveDoc commands

bool CFiveDoc::IsStart()
{
	return m_bStart;
}

BOOL CFiveDoc::StartGame(GameType type /*=HUMAN_VS_HUMAN*/ ,bool  isHumanFirst/* = true*/)
{
	BOOL result = OnNewDocument();
	if(result)
	{
		m_bStart = true;
		m_type = type;
		m_bHumanFirst = isHumanFirst;
	}

	if(type == HUMAN_VS_COMPUTER)
	{
		cp = (CComputerPlayer *)::AfxBeginThread(RUNTIME_CLASS(CComputerPlayer));
		if(!m_bHumanFirst)
		{
			cp->PostThreadMessage(MSG_COMPUTER_TURN,0,0);
		}
	}
	return result;
}

void CFiveDoc::StopGame()
{
	if(m_type == HUMAN_VS_COMPUTER && cp)
	{
		cp->PostThreadMessage(MSG_GAME_OVER,0,0);
		cp = NULL;
	}
	m_bStart = false;
}

int CFiveDoc::PutChess(int x,int y)
{
	int result = m_cb.PutChess(x,y);
	if(result==0 && m_type == HUMAN_VS_COMPUTER)
	{
		int player = m_cb.GetCurrentPlayer();
		if((m_bHumanFirst && player==WHITE_CHESS) || (!m_bHumanFirst && player==BLACK_CHESS))
		{
			ASSERT(cp!=NULL);
			cp->PostThreadMessage(MSG_COMPUTER_TURN,0,0);
		}
	}
	return result;
}